package com.jiajia.server.config;

import com.jiajia.server.config.security.compontent.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author ZSJia
 * @date 2021/8/22 022 - 12:54
 */
@Configuration
@EnableWebSocketMessageBroker   //启用webSocket
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Value("${jwt.tokenHead}")
    private String  tokenHead;
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 指定端点
     * 添加这个endpoints端点，这样在网页可以通过websocket连接上服务
     * 配置websocket服务器地址，可以指定是否启用socketJS
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
                                                //将ws/ep路径注册为stomp的端点，用户连接了这个端点可以进行webSocket通讯
            registry.addEndpoint("/ws/ep")
                                                //允许跨域访问
                                                .setAllowedOrigins("*")
                                            //开启对SocketJS服务
                                                .withSockJS();
    }

    /**
     * 使用了jwt所以需要配置jwt拦截器放行
     *
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                //判断是否是链接，如果是，需要token，并且设用户对象
                if (StompCommand.CONNECT.equals(accessor.getCommand())){
                        //获取token
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    if (!StringUtils.isEmpty(token)){
                        //截取token
                        String authtoken = token.substring(tokenHead.length());
                        //根据token获取用户名
                        String username = jwtTokenUtils.getUserNameFromToken(authtoken);
                        //如果用户名不为空
                        if (!StringUtils.isEmpty(username)){
                            //登录
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            //验证token是否有效，重新设置用户对象
                            if (jwtTokenUtils.validateToken(authtoken,userDetails)){
                                UsernamePasswordAuthenticationToken authenticationToken =
                                        new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }


                return message;
            }
        });
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
                //配置代理域，可以配置多个，配置代理目的地前缀为/queue，可以在配置域与上向客户端推送消息
            registry.enableSimpleBroker("/queue");
    }
}
